package com.dangz.dans.utils;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * http 工具类
 */
public class HttpHander {


    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;
    //private static final int MAX_TIMEOUT = 8000;   //超时时间8s
    private static final int MAX_TIMEOUT = 6000;   //增信同要求  超时时间60s
    private static final int MAX_READ_TIMEOUT = 10000; //读取超时 15s

    static {
        // 设置连接池
        connMgr = new PoolingHttpClientConnectionManager();
        // 设置连接池大小
        connMgr.setMaxTotal(200);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

        RequestConfig.Builder configBuilder = RequestConfig.custom();
        // 设置连接超时
        configBuilder.setConnectTimeout(MAX_TIMEOUT);
        // 设置读取超时
        configBuilder.setSocketTimeout(MAX_READ_TIMEOUT);
        // 设置从连接池获取连接实例的超时
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
        // 在提交请求之前 测试连接是否可用
        configBuilder.setStaleConnectionCheckEnabled(true);
        requestConfig = configBuilder.build();
    }


    /**
     * https get方法
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String get(String url) throws Exception {
        if (url != null) {
            HttpClient httpClient;
            if (url.startsWith("https")) {
                httpClient = getHttpsClient();
            } else {
                httpClient = getHttpClient();
            }

            return get(httpClient, url);
        } else {
            return "url is null";
        }
    }

    /**
     * https post方法
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String post(String url, Map<String, Object> params) throws Exception {
        if (url == null) {
            return "url is null";
        } else {
            HttpClient httpClient;
            if (url.startsWith("https")) {
                httpClient = getHttpsClient();
            } else {
                httpClient = getHttpClient();
            }

            ArrayList paras = new ArrayList();
            Iterator entity = params.keySet().iterator();

            while (entity.hasNext()) {
                String key = (String) entity.next();
                paras.add(new BasicNameValuePair(key, (String) params.get(key)));
            }
            UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(paras, "UTF-8");
            return post(httpClient, url, entity1);
        }
    }

    /**
     * 发送json
     *
     * @param url
     * @param jsonObject
     * @return
     * @throws Exception
     */
    public static String jsonPost(String url, JSONObject jsonObject) throws Exception {
        if (url == null) {
            return "url is null";
        } else {
            HttpClient httpClient;
            if (url.startsWith("https")) {
                httpClient = getHttpsClient();
            } else {
                httpClient = getHttpClient();
            }
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");//解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");

            httpPost.setEntity(entity);
            String content = "";
            try {
                HttpResponse response = httpClient.execute(httpPost);
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                    content = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            } finally {
                httpPost.abort();
            }
            return content;
        }
    }


    /**
     * https post方法
     *
     * @param url
     * @param json
     * @return
     * @throws Exception
     */
    public static String post(String url, String json) throws Exception {
        if (url != null) {
            HttpClient httpClient;
            if (url.startsWith("https")) {
                httpClient = getHttpsClient();
            } else {
                httpClient = getHttpClient();
            }
            StringEntity entity = new StringEntity(json, "UTF-8");
            return post(httpClient, url, entity);
        } else {
            return "url is null";
        }
    }

    /**
     * https post 带header请求头的重载方法
     *
     * @param url
     * @param json
     * @return
     * @throws Exception
     */
    public static String post(String url, String json, String token) throws Exception {
        if (url != null) {
            HttpClient httpClient;
            if (url.startsWith("https")) {
                httpClient = getHttpsClient();
            } else {
                httpClient = getHttpClient();
            }
            StringEntity entity = new StringEntity(json, "UTF-8");
            return post(httpClient, url, entity, token);
        } else {
            return "url is null";
        }
    }

    public static String postp(String url, String json) throws Exception {
        if (url != null) {
            HttpClient httpClient;
            if (url.startsWith("https")) {
                httpClient = getHttpsClient();
            } else {
                httpClient = getHttpClient();
            }

            StringEntity entity = new StringEntity(json, "UTF-8");
            return postp(httpClient, url, entity);
        } else {
            return "url is null";
        }
    }

    /**
     * https get方法
     *
     * @param httpClient
     * @param url
     * @return
     * @throws IOException
     */
    private static String get(HttpClient httpClient, String url) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        httpGet.setConfig(requestConfig);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
        String string;
        StringBuilder builder = new StringBuilder();
        while ((string = bufferedReader.readLine()) != null) {
            builder.append(string);
        }

        httpGet.abort();
        return builder.toString();
    }

    /**
     * https post方法
     *
     * @param httpClient
     * @param url
     * @param entity
     * @return
     * @throws IOException
     */
    private static String post(HttpClient httpClient, String url, HttpEntity entity) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        httpPost.setConfig(requestConfig);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();

        String response = EntityUtils.toString(httpEntity, "utf-8");
        EntityUtils.consume(httpEntity);
        return response;
    }

    /**
     * https post 带请求头的重载方法
     *
     * @param httpClient
     * @param url
     * @param entity
     * @return
     * @throws IOException
     */
    private static String post(HttpClient httpClient, String url, HttpEntity entity, String token) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Authorization", token);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();

        String response = EntityUtils.toString(httpEntity, "utf-8");
        EntityUtils.consume(httpEntity);
        return response;
    }

    private static String postp(HttpClient httpClient, String url, HttpEntity entity) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("content-type", "application/x-www-form-urlencoded");
        HttpResponse httpResponse = httpClient.execute(httpPost);

        String result = null;
        if (httpResponse != null) {
            HttpEntity resEntity = httpResponse.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }
        return result;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();//网页的二进制数据
        outStream.close();
        inStream.close();
        return data;
    }


    /**
     * 统一构造方法http get请求
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String httpGet(String url) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
        String detail = bufferedReader.readLine();
        httpGet.abort();
        return detail;
    }

    /**
     * 统一构造方法http post请求
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String httpPost(String url) throws Exception {
        HttpClient httpClient = getHttpsClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
        String detail = bufferedReader.readLine();
        httpPost.abort();
        return detail;
    }


    private static HttpClient getHttpClient() {
        return HttpClients.createDefault();
    }

    public static HttpClient getHttpsClient() throws Exception {
        SSLContext context = (new SSLContextBuilder()).loadTrustMaterial((KeyStore) null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();
        return HttpClients.custom().setSslcontext(context).build();
    }


    public static String get(String url, Map<String, Object> reqMap) {
        Iterator it = reqMap.keySet().iterator();
        StringBuilder uri = new StringBuilder();
        String response = "";
        try {
            while (it.hasNext()) {
                String k = (String) it.next();
                uri.append(k).append("=").append(reqMap.get(k)).append("&");
            }
            System.out.println((url + "?" + uri.toString().substring(0, uri.toString().length() - 1)).replaceAll(" ", "%20"));
            response = get((url + "?" + uri.toString().substring(0, uri.toString().length() - 1)).replaceAll(" ", "%20"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 发送 POST 请求（HTTP），JSON形式
     *
     * @param apiUrl
     * @param json    json对象
     * @param headers  自定义请求头
     * @return
     */
    public static String doPost(String apiUrl, Object json, Map<String, Object> headers) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        try {
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);

            // 设置请求头
            List<Header> headerList = new ArrayList<Header>(headers.size());
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                Header header = new BasicHeader(entry.getKey(), entry.getValue().toString());
                headerList.add(header);
            }
            httpPost.setHeaders(headerList.toArray(new Header[headers.size()]));
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return httpStr;
    }


    // 可以设置请求头的get
    public static String doGet(String url, Map<String, Object> params, Map<String, Object> headers) {
        String apiUrl = url;
        StringBuffer param = new StringBuffer();
        int i = 0;
        for (String key : params.keySet()) {
            if (i == 0)
                param.append("?");
            else
                param.append("&");
            param.append(key).append("=").append(params.get(key));
            i++;
        }
        apiUrl += param;
        String result = null;
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpGet = new HttpGet(apiUrl);
            // 设置请求头
            List<Header> headerList = new ArrayList<Header>(headers.size());
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                Header header = new BasicHeader(entry.getKey(), entry.getValue().toString());
                headerList.add(header);
            }
            httpGet.setHeaders(headerList.toArray(new Header[headers.size()]));
            HttpResponse response = httpclient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();

            System.out.println("执行状态码 : " + statusCode);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, "UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }



    /**
     * 发送 POST 请求（HTTP），JSON形式
     *
     * @param apiUrl
     * @param json
     *            json对象
     * @return
     */
    public static String doPost(String apiUrl, Object json) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        try {
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return httpStr;
    }

	/**
	 * 发送 POST 请求（HTTP），K-V形式
	 *
	 * @param apiUrl
	 *            API接口URL
	 * @param params
	 *            参数map
	 * @return
	 */
	public static String doPost(String apiUrl, Map<String, Object> params) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String httpStr = null;
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;

		try {
			httpPost.setConfig(requestConfig);
			List<NameValuePair> pairList = new ArrayList<>(params.size());
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
				pairList.add(pair);
			}
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
			response = httpClient.execute(httpPost);
			System.out.println(response.toString());
			HttpEntity entity = response.getEntity();
			httpStr = EntityUtils.toString(entity, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

    /**
     * HTTP form表单上传HTML文件
     * @param serverUrl 服务端地址
     * @param textParts
     * @param localFilePath 本地文件路径
     * @param serverFieldName 服务端文件字段名
     * @return
     * @throws Exception
     */
    public static Integer uploadFile(String serverUrl, Map<String, String> textParts,String localFilePath,String serverFieldName) throws Exception{
        if (serverUrl == null) {
            return null;
        }
        //1、创建HttpClient
        HttpClient httpClient;
        if (serverUrl.startsWith("https")) {
            httpClient = getHttpsClient();
        } else {
            httpClient = getHttpClient();
        }
        HttpPost post = new HttpPost(serverUrl);
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //2、设置 multipart/form-data text表单
            if (textParts != null) {
                Iterator<Map.Entry<String, String>> iter = textParts.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry<String, String> entry = iter.next();
                    String paramName = entry.getKey();
                    String paramValue = entry.getValue();
                    builder.addTextBody(paramName, paramValue, ContentType.DEFAULT_TEXT);
                }
            }
            FileBody binFileBody = new FileBody(new File(localFilePath));
            builder.addPart(serverFieldName,binFileBody);
            HttpEntity reqEntity = builder.build();
            // 4、设置POST请求实体
            post.setEntity(reqEntity);
            // 6、得到response
            HttpResponse response = httpClient.execute(post);
            // 7、得到 http status code
            int resStatu = response.getStatusLine().getStatusCode();
            return resStatu;
        } finally {
            post.abort();
        }
    }



}
